extension YLMap<K, V> on Map<K, V> {
  Map<K, V> copy() {
    return Map<K, V>.from(this);
  }

  Map<K, V> removeNull() {
    var result = Map<K, V>.from(this);
    if (result.isNotEmpty) {
      result = Map<K, V>.from(_oremoveNull(result));
    }
    return result;
  }

  Map<K, V> trim() {
    var result = Map<K, V>.from(this);
    // result.removeWhere((key, value) => value == null || value == '');
    if (result.isNotEmpty) {
      result = Map<K, V>.from(_oremoveNull(result, true));
    }
    return result;
  }

  dynamic _oremoveNull(dynamic params, [bool isAll = false]) {
    if (params is Map) {
      final filteredMap = {};
      params.forEach((key, value) {
        final processedValue = _oremoveNull(value, isAll); // 递归处理嵌套结构
        if (processedValue != null) {
          if (isAll) {
            if (processedValue != '') {
              filteredMap[key] = processedValue;
            }
          } else {
            filteredMap[key] = processedValue;
          }
        }
      });
      return filteredMap; // 可选：移除空 Map
    } else if (params is List) {
      final filteredList = [];
      for (var item in params) {
        final processedItem = _oremoveNull(item); // 递归处理嵌套结构
        if (processedItem != null) {
          filteredList.add(processedItem);
        }
      }
      return filteredList; // 可选：移除空 List
    }
    return params; // 非集合类型直接返回（若为 null 则被上层过滤）
  }

  String queryString() {
    var result = Map<String, dynamic>.from(this);
    return Uri(queryParameters: _convertNonNullValues(result)).query;
  }

  Map<String, String> _convertNonNullValues(Map<String, dynamic> obj) {
    return obj.entries
        .where((entry) =>
            entry.value != null &&
            entry.value != "null" &&
            entry.value != "" &&
            entry.value is! bool) // 过滤 null 值
        .map((entry) => MapEntry(entry.key, entry.value.toString()))
        .toList()
        .asMap()
        .map((_, entry) => MapEntry(entry.key, entry.value));
  }
}
